<?php


namespace app\user\controller;

use app\common\controller\Base;
use app\common\model\Bank;
use app\common\model\UserBank as userBankModel;
use think\Request;
use app\common\lib\Util;

class UserBank extends Base
{
    //用户绑定的银行卡列表
    public function index(userBankModel $userBankModel)
    {
        $userBankList = $userBankModel->field('id,bank_id,bank_number')->with(['bank' => function ($query) {
            $query->field('id,name');
        }])
            ->where(['user_id' => $this->userId])->select();
        return Util::apiResponse(['user_bank_list' => $userBankList], '', 200);
    }

    //
    public function delete(Request $request,userBankModel $userBankModel)
    {
        $id = $request->param('id');
        $exist = $userBankModel->where(['id'=>$id,'user_id'=>$this->userId])->find();
        if(!$exist){
            return Util::apiResponse([], '参数错误', 400);
        }
        $result  = $userBankModel->destroy(['id'=>$id,'user_id'=>$this->userId]);
        if(!$result){
            return Util::apiResponse([], '操作失败', 400);
        }
        return Util::apiResponse([], '操作成功', 200);
    }

    //银行卡种类
    public function bankList()
    {
        $bankList = Bank::field('id,name')->select();
        return Util::apiResponse(['bank_list' => $bankList], '', 200);
    }

    //银行卡的添加
    public function add(Request $request, userBankModel $userBankModel)
    {
        $cardOwner = $request->card_owner;
        $bankNumber = $request->bank_number;
        $bankId = intval($request->bank_id);
        $bankType = intval($request->bank_type);
        if (empty($cardOwner) && $cardOwner != '0') {
            return Util::apiResponse([], '请填写持卡人', 400);
        }
        if (empty($bankNumber) && $bankNumber != '0') {
            return Util::apiResponse([], '请填写卡号', 400);
        }
        $exist = Bank::where(['id' => $bankId])->find();
        if (!$exist) {
            return Util::apiResponse([], '参数错误', 400);
        }
        //1 储蓄卡 2 信用卡
        if (!in_array($bankType, [1, 2])) {
            return Util::apiResponse([], '参数错误', 400);
        }
        $bankData = [
            'user_id' => $this->userId,
            'card_owner' => $cardOwner,
            'bank_number' => $bankNumber,
            'bank_id' => $bankId,
            'bank_type' => $bankType
        ];
        $ins = $userBankModel->save($bankData);
        if (!$ins) {
            return Util::apiResponse([], '操作失败', 400);
        }
        return Util::apiResponse([], '操作成功', 200);
    }
}